package com.summer.data.jql.builder.from;

import com.summer.data.Jsql;
import com.summer.data.dialect.Dialect;
import com.summer.data.jql.Context;
import com.summer.data.jql.JsqlAble;
import com.summer.data.jql.behavior.FilterAble;
import com.summer.data.jql.behavior.TableAble;
import com.summer.data.jql.builder.OnBuilder;

/**
 * @author 345480567@qq.com
 */

public class JoinNode implements JsqlAble {

    protected JOIN_TYPE joinType;

    public TableAble tableAble;

    Context ctx;

    OnBuilder onBuilder;

    public JoinNode(Context ctx, JOIN_TYPE joinType, TableAble tableAble) {
        this.ctx = ctx;
        this.joinType = joinType;
        this.tableAble = tableAble;
        this.onBuilder = new OnBuilder(ctx);
    }

    public void and(FilterAble exp) {
        onBuilder.and(exp);
    }

    public void or(FilterAble exp) {
        onBuilder.or(exp);
    }

    protected void buildJoinSql(Jsql jsql, Dialect dialect) {
        String alias = ctx.getAlias(tableAble);

        if (alias == null || alias.trim().isEmpty()) {
            Jsql.format(jsql, "  %s %s", joinType, tableAble.getTableSql(dialect));
        } else {
            Jsql.format(jsql, "  %s %s %s", joinType, tableAble.getTableSql(dialect), alias);
        }
    }


    @Override
    public Jsql buildJsql(Dialect dialect) {
        Jsql jsql = new Jsql();
        buildJoinSql(jsql, dialect);
        if (onBuilder.size()>0) {
            jsql.append(System.lineSeparator());
            jsql.append(onBuilder.buildJsql(dialect));
        }
        return jsql;
    }
}

